package com.a1anwang.okble.demo.ability;

import com.a1anwang.okble.beacon.OKBLEBeBeaconManager;
import com.a1anwang.okble.common.OKBLEDataUtils;
import com.a1anwang.okble.demo.ResourceTable;
import com.a1anwang.okble.demo.base.BaseAbility;
import com.a1anwang.okble.demo.utils.TextUtilsEx;
import com.a1anwang.okble.demo.utils.ToastUtil;
import com.a1anwang.okble.demo.views.CompleteUUIDInputPopupWindow;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.bluetooth.BluetoothHost;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by a1anwang.com on 2018/5/30.
 */

public class BeIBeaconAbility extends BaseAbility {
    OKBLEBeBeaconManager beBeaconManager;
    private BluetoothHost host;
    private Image btnLeft;
    private TextField editMajor;
    private TextField editMinor;
    private String beginMajor;
    private String beginMinor;
    EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner());

    @Override
    public boolean isFullScreen() {
        return false;
    }

    @Override
    public void setContentLayout() {
        setUIContent(ResourceTable.Layout_ability_be_ibeacon);
    }

    @Override
    public void beforeInitView() {
        beBeaconManager = new OKBLEBeBeaconManager(this);
        beBeaconManager.setOKBLEBeBeaconListener(startBeaconListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        beBeaconManager.stop();
    }

    @Override
    public void initView() {
        editMajor = (TextField) findComponentById(ResourceTable.Id_edit_major);
        editMinor = (TextField) findComponentById(ResourceTable.Id_edit_minor);
        btnLeft = (Image) findComponentById(ResourceTable.Id_btn_left);
        btnLeft.setClickedListener(this);
        host = BluetoothHost.getDefaultHost(this);
        setHeadVisibility(Component.VISIBLE);
        setTitle("Work as an iBeacon");
        findComponentById(ResourceTable.Id_btn_start).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_stop).setClickedListener(this);
        findComponentById(ResourceTable.Id_layout_uuid).setClickedListener(this);
        editMajor.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                if (!isNumeric(s)) {
                    editMajor.setText(beginMajor);
                    return;
                }
                beginMajor = s;
            }
        });

        editMinor.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                if (!isNumeric(s)) {
                    editMinor.setText(beginMinor);
                    return;
                }
                beginMinor = s;
            }

        });
    }

    private boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    @Override
    public void afterInitView() {
    }

    @Override
    public void onClickEvent(Component v) {
        switch (v.getId()) {
            case ResourceTable.Id_btn_start:
                if (host.getBtState() == BluetoothHost.STATE_ON) {

                    if (isNumeric(editMajor.getText()) || isNumeric(editMinor.getText())) {
                        startAdvertising();
                    } else {
                        return;
                    }

                } else {
                    ToastUtil.toast(this, "请打开手机蓝牙");
                }
                break;
            case ResourceTable.Id_btn_stop:
                beBeaconManager.stop();
                break;
            case ResourceTable.Id_layout_uuid:
                showHexInput();
                break;
            case ResourceTable.Id_btn_left:
                onBackPressed();
                break;
            default:
                break;
        }
    }


    private void showHexInput() {
        CompleteUUIDInputPopupWindow popupWindow = new CompleteUUIDInputPopupWindow(this);
        popupWindow.showAt();
        popupWindow.setInputListener(new CompleteUUIDInputPopupWindow.InputListener() {
            @Override
            public void onInputComplete(String value) {
                TextField editUuid = (TextField) findComponentById(ResourceTable.Id_edit_uuid);
                editUuid.setText(value);
            }
        });


    }

    private void startAdvertising() {
        TextField editUuid = (TextField) findComponentById(ResourceTable.Id_edit_uuid);

        String uuid = editUuid.getText().toString().toUpperCase();
        boolean isvaliduuid = OKBLEDataUtils.isValidUUID(uuid);
        if (!isvaliduuid) {
            ToastUtil.toast(this, "UUID is not valid");
            return;
        }
        int major = -1;
        if (!TextUtilsEx.isEmpty(editMajor.getText().toString())) {
            major = Integer.parseInt(editMajor.getText().toString());
        }
        int minor = -1;
        if (!TextUtilsEx.isEmpty(editMinor.getText().toString())) {
            minor = Integer.parseInt(editMinor.getText().toString());
        }
        if (major < 0 || major > 65535) {
            ToastUtil.toast(this, "major ranges：[0- 65535]");
            return;
        }
        if (minor < 0 || minor > 65535) {
            ToastUtil.toast(this, "minor ranges：[0- 65535]");
            return;
        }
        beBeaconManager.startIBeacon(uuid, major, minor);
    }

    OKBLEBeBeaconManager.OKBLEStartBeaconListener startBeaconListener = new OKBLEBeBeaconManager.OKBLEStartBeaconListener() {
        @Override
        public void onStartSuccess() {
            eventHandler.postTask(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.toast(mContext, "start success");
                }
            });
        }

        @Override
        public void onStartFailure(String errMsg) {
            eventHandler.postTask(new Runnable() {
                @Override
                public void run() {
                    ToastUtil.toast(mContext, "start failed:" + errMsg);
                }
            });
        }
    };
}
